package net.wanho.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.wanho.properties.AlipayProperties;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Author：汤小洋
 * Date：2024-01-18 15:56
 * Description：<描述>
 */
@RestController
@RequestMapping("/alipay")
@CrossOrigin
@Slf4j
public class AlipayController {

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private AlipayTradePagePayRequest payRequest;

    @Resource
    private AlipayProperties alipayProperties;

    /**
     * 支付方法
     */
    @SneakyThrows
    @PostMapping("/pay")
    public void pay(String orderNo, String subject, Double totalAmount, HttpServletResponse response){
        // 封装业务参数
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo); // 订单号
        bizContent.put("subject", subject); //  订单名称
        bizContent.put("total_amount", totalAmount); // 订单总金额
        bizContent.put("product_code","FAST_INSTANT_TRADE_PAY"); // 产品码，固定值
        bizContent.put("timeout_express","15m"); // 超时时间，15分钟
        payRequest.setBizContent(bizContent.toString());

        // 向支付宝发送支付请求
        String result = alipayClient.pageExecute(payRequest).getBody();
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().print(result);
    }

    /**
     * 异步通知
     */
    @SneakyThrows
    @PostMapping("/notify")
    public String notify(@RequestParam Map<String,String> params){
        System.out.println(params);
        /**
         * 进行验签操作，防止签名被篡改
         */
        boolean flag = AlipaySignature.rsaCheckV1(params, alipayProperties.getAlipayPublicKey(), alipayProperties.getCharset(), alipayProperties.getSignType());
        if(!flag){
            log.info("验证签名失败！");
            return "fail";
        }

        /**
         * 判断返回的订单号、订单总金额等是否与发送的一致，防止数据被篡改
         */
        String out_trade_no = params.get("out_trade_no");
        String total_amount = params.get("total_amount");

        /**
         * 判断支付宝返回的状态是否正常
         */
        String trade_status = params.get("trade_status");
        if(!trade_status.equals("TRADE_SUCCESS")){
            log.info("交易失败！");
            return "fail";
        }

        /**
         * 更新相应的订单状态，例如将订单标记为已支付、更新库存等
         */
        // orderService.updateOrderStatus();

        return "success";
    }



}
